#include "AdminLogin.hpp"
#include "AdminGUI.hpp"
#include "AdminRegister.hpp"
#include "tools/Hash.hpp"
#include "tools/ReadAndWeite.hpp"

#include <QColor>
#include <QFormLayout>
#include <QGraphicsDropShadowEffect>
#include <QGuiApplication>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QPainter>
#include <QPixmap>
#include <QPushButton>
#include <QRect>
#include <QScreen>
#include <QSizePolicy>
#include <QVBoxLayout>

AdminLogin::AdminLogin(QWidget *parent)
    : QMainWindow(parent), isDragging(false) {
  backgroundImage.load(
      "/home/ccy/code_workspace/cpp_finall/resource/img/wave.png");

  setupUI();
  setupConnections();
  setWindowTitle("登录");
}
AdminLogin::~AdminLogin() {}

void AdminLogin::setupUI() {
  centralWidget = new QWidget(this);
  setCentralWidget(centralWidget);
  // 获取屏幕尺寸
  QScreen *screen = QGuiApplication::primaryScreen();
  QRect screenGeometry = screen->geometry();
  int screenWidth = screenGeometry.width();
  int screenHeight = screenGeometry.height();

  // 设置窗口大小为屏幕的40%
  int windowWidth = static_cast<int>(screenWidth * 0.6);
  int windowHeight = static_cast<int>(screenHeight * 0.6);
  resize(windowWidth, windowHeight);

  // 主布局使用QHBoxLayout，分为左右两部分
  QHBoxLayout *mainHLayout = new QHBoxLayout(centralWidget);
  mainHLayout->setContentsMargins(0, 0, 0, 0);
  mainHLayout->setSpacing(0);

  // 左边部分 - 装饰图
  QWidget *leftWidget = new QWidget(centralWidget);
  leftWidget->setFixedWidth(static_cast<int>(windowWidth * 0.45));
  // 添加波浪背景
  QLabel *waveLabel = new QLabel(leftWidget);
  QPixmap wavePixmap(
      "/home/ccy/code_workspace/cpp_finall/resource/img/wave.png");

  waveLabel->setPixmap(wavePixmap.scaled(leftWidget->width(), windowHeight,
                                         Qt::KeepAspectRatioByExpanding,
                                         Qt::SmoothTransformation));

  waveLabel->setAlignment(Qt::AlignCenter);
  waveLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

  QLabel *iconLabel = new QLabel(leftWidget);
  QPixmap iconPixmap(
      "/home/ccy/code_workspace/cpp_finall/resource/img/login-mobile.svg");
  iconLabel->setPixmap(
      iconPixmap.scaled(static_cast<int>(leftWidget->width() * 0.6),
                        static_cast<int>(leftWidget->width() * 0.6),
                        Qt::KeepAspectRatio, Qt::SmoothTransformation));
  iconLabel->setAlignment(Qt::AlignCenter);

  QVBoxLayout *leftLayout = new QVBoxLayout(leftWidget);
  leftLayout->addWidget(waveLabel);
  leftLayout->addWidget(iconLabel);
  leftWidget->setLayout(leftLayout);
  leftLayout->setStretch(0, 2);
  leftLayout->setStretch(1, 1);
  leftWidget->setStyleSheet("background-color: #4285f4;"); // Google蓝色

  // 右边部分 - 登录表单
  QWidget *rightWidget = new QWidget(centralWidget);
  rightWidget->setStyleSheet("background-color: white;");

  mainLayout = new QVBoxLayout(rightWidget);
  mainLayout->setContentsMargins(40, 40, 40, 40);
  mainLayout->setSpacing(20);

  // 标题和副标题
  titleLabel = new QLabel("欢迎回来", rightWidget);
  titleLabel->setStyleSheet("font-size: 48px; font-weight: bold; color: #333;");
  titleLabel->setAlignment(Qt::AlignLeft);

  subtitleLabel = new QLabel("请登录您的账号", rightWidget);
  subtitleLabel->setStyleSheet("font-size: 32px; color: #666;");
  subtitleLabel->setAlignment(Qt::AlignLeft);

  // 登录表单
  QWidget *formWidget = new QWidget(rightWidget);
  QFormLayout *formLayout = new QFormLayout(formWidget);
  formLayout->setSpacing(15);

  adminnameEdit = new QLineEdit(formWidget);
  adminnameEdit->setPlaceholderText("用户名/手机号码");
  adminnameEdit->setStyleSheet("QLineEdit { padding: 12px; border: 1px solid "
                               "#ddd; border-radius: 8px; font-size: 28px; }");

  // 为输入框添加图标
  QLabel *userIconLabel = new QLabel(formWidget);
  QPixmap userIcon(
      "/home/ccy/code_workspace/cpp_finall/resource/img/avatar.svg");
  userIconLabel->setPixmap(
      userIcon.scaled(20, 20, Qt::KeepAspectRatio, Qt::SmoothTransformation));
  QHBoxLayout *userLayout = new QHBoxLayout();
  userLayout->addWidget(userIconLabel);
  userLayout->addWidget(adminnameEdit);

  // 密码输入框
  passwordEdit = new QLineEdit(formWidget);
  passwordEdit->setPlaceholderText("请输入密码");
  passwordEdit->setEchoMode(QLineEdit::Password);
  passwordEdit->setStyleSheet("QLineEdit { padding: 12px; border: 1px solid "
                              "#ddd; border-radius: 8px; font-size: 28px; }");

  // 为密码框添加图标
  QLabel *lockIconLabel = new QLabel(formWidget);
  QPixmap lockIcon(
      "/home/ccy/code_workspace/cpp_finall/resource/img/authentication.svg");
  lockIconLabel->setPixmap(
      lockIcon.scaled(20, 20, Qt::KeepAspectRatio, Qt::SmoothTransformation));
  QHBoxLayout *passLayout = new QHBoxLayout();
  passLayout->addWidget(lockIconLabel);
  passLayout->addWidget(passwordEdit);

  formLayout->addRow("", userLayout);
  formLayout->addRow("", passLayout);

  loginButton = new QPushButton("登录", rightWidget);
  loginButton->setStyleSheet(
      "QPushButton { background-color: #4285f4; color: white; border: none; "
      "padding: 12px; border-radius: 8px; font-size: 26px; font-weight: bold; "
      "} "
      "QPushButton:hover { background-color: #3367d6; }");
  loginButton->setMinimumHeight(45);

  // 添加阴影效果
  QGraphicsDropShadowEffect *buttonShadow = new QGraphicsDropShadowEffect();
  buttonShadow->setBlurRadius(15);
  buttonShadow->setColor(QColor(66, 133, 244, 80));
  buttonShadow->setOffset(0, 4);
  loginButton->setGraphicsEffect(buttonShadow);

  // 添加所有组件到主布局
  mainLayout->addWidget(titleLabel);
  mainLayout->addWidget(subtitleLabel);
  mainLayout->addSpacing(20);
  mainLayout->addWidget(formWidget);

  mainLayout->addSpacing(10);
  mainLayout->addWidget(loginButton);
  mainLayout->addSpacing(20);

  mainLayout->addStretch();

  // 将两个面板添加到主布局
  mainHLayout->addWidget(leftWidget);
  mainHLayout->addWidget(rightWidget);

  // 设置窗口样式
  setStyleSheet("font-family: 'Segoe UI', Arial, sans-serif;");
  setAttribute(Qt::WA_TranslucentBackground);
  setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint);
}

void AdminLogin::setupConnections() {
  connect(loginButton, &QPushButton::clicked, this,
          &AdminLogin::onLoginButtonClicked);
}

void AdminLogin::paintEvent(QPaintEvent *event) {
  QMainWindow::paintEvent(event);
  // 绘制背景图片
  QPainter painter(this);
  if (!backgroundImage.isNull()) {
    backgroundImage = backgroundImage.scaled(
        this->size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
    painter.drawPixmap(0, 0, backgroundImage);
  }
}
// 实现鼠标事件处理函数，用于支持无边框窗口的拖拽
void AdminLogin::mousePressEvent(QMouseEvent *event) {
  if (event->button() == Qt::LeftButton) {
    isDragging = true;
    dragPosition = event->globalPos() - frameGeometry().topLeft();
    event->accept();
  }
}

void AdminLogin::mouseMoveEvent(QMouseEvent *event) {
  if (event->buttons() & Qt::LeftButton && isDragging) {
    move(event->globalPos() - dragPosition);
    event->accept();
  }
}

void AdminLogin::mouseReleaseEvent(QMouseEvent *event) {
  if (event->button() == Qt::LeftButton) {
    isDragging = false;
    event->accept();
  }
}

void AdminLogin::onLoginButtonClicked() {
  QString adminname = adminnameEdit->text();
  QString password = passwordEdit->text();

  // 登录成功
  bool loginSuccess = false; // 这里应替换为实际的验证结果

  nlohmann::json adminJson;
  read_from_file(
      "/home/ccy/code_workspace/cpp_finall/resource/Admin/admin.json",
      adminJson);
  if (adminJson.contains("name") && adminJson.contains("password")) {
    std::string adminName = adminJson["name"].get<std::string>();
    std::string adminPassword = adminJson["password"].get<std::string>();
    if (adminName == adminname.toStdString() &&
        adminPassword == tools::calculateHash(password.toStdString())) {
      loginSuccess = true;
    }
  }
  if (!loginSuccess) {
    QMessageBox::critical(this, "登录失败", "用户名或密码错误");
    return;
  }
  // 登录成功后，打开管理员界面

  AdminGUI *adminGUI = new AdminGUI();
  adminGUI->setAttribute(Qt::WA_DeleteOnClose);
  adminGUI->setWindowTitle("管理员界面 - " + adminname);
  adminGUI->resize(2580, 1600);
  adminGUI->show();
  close(); // 关闭登录窗口
}
